<?php

namespace mongrove;

/**
 * The DatabaseManager is a central instance responsible for resolving
 * MongoDB handles for given collection- and database names.
 *
 * @author Gido Hakvoort <gido@hakvoort.it>
 * @author Michiel Hakvoort <michiel@hakvoort.it>
 *
 */
class DatabaseManager {

    protected $databases = array();

    protected $collections = array();

    /**
     * Instantiate the DatabaseManager backed by the given selection
     * of Mongo database handles.
     *
     * @param array[MongoDB] $databases
     */
    public function __construct(array $databases) {

        foreach($databases as $database) {

            $name = $database->__toString();
            $this->databases[$name] = $database;

            $collections = $database->listCollections();

            // map existing collections to database
            foreach($collections as $collection) {
			    $this->collections[$collection->getName()] = $name;
		    }
	    }
    }

    /**
     * Resolve a MongoDB handle for the given Mongo collection name and
     * database name combination.
     *
     * @param string $collectionName
     * @param string $databaseName
     *
     * @return \MongoDB
     */
    public function getDatabase($collectionName, $databaseName) {

        // return the requested database if available
        if($databaseName !== null && isset($this->databases[$databaseName])) {
            return $this->databases[$databaseName];
        }

        // associate collection with first database
        if($collectionName !== null && !isset($this->collections[$collectionName])) {
            reset($this->databases);
            $this->collections[$collectionName] = key($this->databases);
        }

        // return the database associated with this collection
        return $this->databases[$this->collections[$collectionName]];
    }

    /**
     * Get the Mongo database handles managed by the DatabaseManager.
     *
     * @return array[MongoDB]
     */
    public function getDatabases() {
        return $this->databases;
    }

}
